package com.lihang0328.groupmessageangel;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import jxl.Sheet;
import jxl.Workbook;

public class FileUtils {
    /**
     * 把content uri转为 file路径
     * @param context
     * @param uri
     * @return
     */
    public static String getPath(Context context, Uri uri) {
        System.out.println("lihangfile:" + uri);
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = { "_data" };
            Cursor cursor = null;
            String filePath = null;
            try {
                cursor = context.getContentResolver().query(uri, projection,null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    System.out.println("get curcor  "+ cursor.moveToFirst()+" " +cursor.getString(column_index));
                    filePath =  cursor.getString(column_index);
                }
//                String[] filePathColumn = {MediaStore.MediaColumns.DATA};
//                cursor = context.getContentResolver().query(uri, filePathColumn, null, null, null);
//                cursor.moveToFirst();
//                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//                filePath = cursor.getString(columnIndex);
//                System.out.println("get curcor  "+ cursor.moveToFirst()+" " +cursor.getString(columnIndex));
                System.out.println("filepath:" + filePath);
                cursor.close();
                return filePath;
            } catch (Exception e) {
                System.out.println("lihangfile:exception");
                // Eat it
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    /**
     * 是否存在此name的联系人
     * @param context
     * @param name
     * @return
     */
    public static boolean DoHaveName(Context context, String name) {
        List<Map<String ,Object>> data=new ArrayList<>();
        ContentResolver cr = context.getContentResolver();
        Uri uri=Uri.parse("content://com.android.contacts/raw_contacts");
        Cursor cursor= cr.query(uri,null,null,null,null);
        while(cursor.moveToNext()) {
            int id=cursor.getInt(cursor.getColumnIndex("_id"));
            Uri uriData=Uri.parse("content://com.android.contacts/raw_contacts/"+id+"/data");
            Cursor contactData= cr.query(uriData,null,null,null,null);
            String aa="";
            while(contactData.moveToNext()){
                String type=contactData.getString(contactData.getColumnIndex("mimetype"));
                if(type.equals("vnd.android.cursor.item/name")) {
                    aa=contactData.getString(contactData.getColumnIndex("data1"));
                }
            }
            if(aa.trim().equals(name)) return true;
        }
        return false;
    }
    /**
     * 读取通讯录内容
     * @param context
     * @return 返回一个List<Map>，其中Name标识姓名，Phone标识电话号码
     */
    public static List<Map<String ,Object>> readAddress(Context context) {
        System.out.println("lihangfiletxt3");
        List<Map<String ,Object>> data=new ArrayList<>();
        Map<String, Boolean> mp = new HashMap<>();
        ContentResolver cr = context.getContentResolver();
        data = new ArrayList<>();
        Uri uri=Uri.parse("content://com.android.contacts/raw_contacts");
        Cursor cursor= cr.query(uri,null,null,null,null);
        while(cursor.moveToNext()) {
            int id=cursor.getInt(cursor.getColumnIndex("_id"));
            Uri uriData=Uri.parse("content://com.android.contacts/raw_contacts/"+id+"/data");
            Cursor contactData= cr.query(uriData,null,null,null,null);
            //用来装姓名
            String aa="";
            //用来装号码
            String bb="";
            while(contactData.moveToNext()){
                String type=contactData.getString(contactData.getColumnIndex("mimetype"));
                //如果获取的是vnd.android.cursor.item/phone_v2则是号码
                if(type.equals("vnd.android.cursor.item/phone_v2")){
                    bb=contactData.getString(contactData.getColumnIndex("data1")).trim();
                    //如果获取的是vnd.android.cursor.item/name则是姓名
                }else if(type.equals("vnd.android.cursor.item/name")) {
                    aa=contactData.getString(contactData.getColumnIndex("data1")).trim();
                }
            }
            //将用户名和号码放入Map集合中
            Map<String,Object> map=new HashMap<>();
            if(aa != null && bb != null && !aa.equals("") && !bb.equals("")) {
                System.out.println("lihang1:"+ aa + " " + bb);
                if(!mp.containsKey(aa+bb)) {
                    map.put("Name", aa);
                    map.put("Phone", bb);
                    data.add(map);
                    mp.put(aa + bb, true);
                }
            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            data.sort(new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    return o1.get("Name").toString().compareToIgnoreCase(o2.get("Name").toString());
                }
            });
        }
        return data;
    }

    /**
     * 读取Txt内容
     * @param context
     * @param path
     * @return 返回一个List<Map>，其中Name标识姓名，Phone标识电话号码
     */
    public static List<Map<String ,Object>> readTxt(Context context, String path) {
        System.out.println("lihangfiletxt2");
        List<Map<String ,Object>> data=new ArrayList<>();
        File file = new File(path);
        try {
            InputStream is = new FileInputStream(file);
            InputStreamReader inputreader = new InputStreamReader(is);
            BufferedReader buffreader = new BufferedReader(inputreader);
            String line;
            while((line = buffreader.readLine())!= null) {
                String[] str = line.split("\\s+");
                if(str.length != 2) continue;
                Map<String,Object> map=new HashMap<>();
                for(String s : str) {
                    if(s.matches("[0-9]*")) map.put("Phone",str[1]);
                    else map.put("Name",str[0]);
                }
                data.add(map);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }
    /**
     * 读取Excel内容
     * @param context 上下文
     * @param path 通讯录文件路径
     * @return 返回一个List<Map>，其中Name标识姓名，Phone标识电话号码
     */

//path="/storage/emulated/0/documents/test.xls";
    public static List<Map<String ,Object>> readExcel(Context context, String path){
        if(path.matches(".*(txt)$")) return readTxt(context, path);
        List<Map<String ,Object>> data=new ArrayList<>();
        try {
            System.out.println("lihang3:path"+path);
            File file = new File(path);
            InputStream is = new FileInputStream(file);
            Workbook book = Workbook.getWorkbook(is);
            int num = book.getNumberOfSheets();
            // 获得第一个工作表对象
            Sheet sheet = book.getSheet(0);
            int Rows = sheet.getRows();         //行
            int Cols = sheet.getColumns();      //列
            //姓名单元格
            int colsOfName=0;
            int rolsOfName=0;
            //电话单元格
            int colsOfNum=0;
            int rolsOfNum=0;
            Log.i("File操作日志","查找姓名属性");
            for (int i = 0; i < Cols; ++i) {
                for (int j = 0; j < Rows; ++j) {
                    // getCell(Col"列",Row"行")获得单元格的值
                    if(sheet.getCell(i,j).getContents().equals("姓名") ||sheet.getCell(i,j).getContents().equals("名字")){
                        colsOfName=i;
                        rolsOfName=j;
                        Log.i("File操作日志","已经找到姓名属性");
                        break;
                    }
                }
            }
            Log.i("File操作日志","查找电话属性");
            for (int i = 0; i < Cols; ++i) {
                for (int j = 0; j < Rows; ++j) {
                    if(sheet.getCell(i,j).getContents().equals("电话") ||sheet.getCell(i,j).getContents().equals("联系电话")
                            ||sheet.getCell(i,j).getContents().equals("电话号码") ||sheet.getCell(i,j).getContents().equals("手机号码")){
                        colsOfNum=i;
                        rolsOfNum=j;
                        Log.i("File操作日志","已经找到电话属性");
                        break;
                    }
                }
            }
            for(int i1=rolsOfName+1,i2=rolsOfNum+1;i1<Rows;i1++,i2++){
                if(!sheet.getCell(colsOfName,i1).getContents().equals("") && !sheet.getCell(colsOfNum,i2).getContents().equals("")){
                    Map<String,Object> map=new HashMap<>();
                    map.put("Name",sheet.getCell(colsOfName,i1).getContents());
                    map.put("Phone",sheet.getCell(colsOfNum,i2).getContents());
                    Log.i("File操作日志",sheet.getCell(colsOfName,i1).getContents()+sheet.getCell(colsOfNum,i2).getContents());
                    data.add(map);
                }
            }
            book.close();
        } catch (Exception e) {
            Toast.makeText(context,"通讯录读取错误",Toast.LENGTH_SHORT).show();
        }
        return data;
    }
}